class ArticlesController < ApplicationController
  layout "application",:except => [:add_article_my_self,:edit_article_my_self]
  protect_from_forgery :except => [:a_upload_fi]
 
#  caches_page :index,:show

  def index
    @articles = Article.paginate(:per_page => 3,:page => params[:page],:order => "id desc")
  end

  def show
		@article = Article.find_by_permalink(params[:id])
    @title   = @article.title if @article
    render :text => "没有文章" if @article.nil?
  end

  def add_article_my_self
    @article = Article.new
		@categories = Category.all
  end

  def edit_article_my_self
		@article = Article.find_by_permalink(params[:id])
  end

  def create
    @article = Article.new(params[:article])
    @article.content = params[:content]
		@article.category_id = params[:category] if params[:category]
    if @article.save
      flash[:notice] = 'Article was successfully created.'
      redirect_to(@article)  
    else
      render :text => "error" 
    end
  end

  def update
    @article = Article.find_by_permalink(params[:id])
    if @article.update_attributes(params[:article])
      params[:categories].each do |e|
        c = Category.find(e) 
        @article.categories << c if !@article.categories.include?(c)
      end
      flash[:notice] = 'Article was successfully updated.'
      redirect_to(:action => :show) 
    else
      render :action => "edit"
    end
  end
  
  def add_comment
    @article = Article.find_by_id(params[:id])
    @comment = Comment.new(:name => params[:name],:email => params[:email],:content => params[:message],:article_id => params[:id])
    if @comment.save
      flash[:notice] = "谢谢"
    else
      flash[:notice] = "error"
    end

    redirect_to :action => "show",:id => @article.permalink
  end

  def a_upload_fi
    upload_file = UploadFile.new
    upload_file.attachment = params[:upload_file]
    if upload_file.save
      render :text => "#{upload_file.attachment}<br/>"
    else
      render :text => "error"
    end
  end

  protected

  def expire_article_page(record)
    page = Article.count / 8
    page += 1 if (Article.count % 8) > 0
    current_page = record.id  / page
    current_page = page - current_page + 1
    expire_page(:action => "index",:id => current_page)
  end

end





